package com.javaeedev.junit;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

public class ServiceImpl implements Service {

    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void signon(String username, String password) {
        if(username==null || password==null)
            throw new NullPointerException();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = dataSource.getConnection();
            ps = conn.prepareStatement("select * from User as u where u.username=? and u.password=?");
            ps.setString(1, username);
            ps.setString(2, password);
            rs = ps.executeQuery();
            if(!rs.next())
                throw new RuntimeException("Sign on failed.");
        }
        catch(SQLException sqle) {
            throw new RuntimeException(sqle);
        }
        finally {
            if(rs!=null) {
                try {
                    rs.close();
                }
                catch(SQLException e) {}
            }
            if(ps!=null) {
                try {
                    ps.close();
                }
                catch(SQLException e) {}
            }
            if(conn!=null) {
                try {
                    conn.close();
                }
                catch(SQLException e) {}
            }
        }
    }

}
